<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('./import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{ prop: 'timeOfEntry', order: 'ascending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="scope">
              类型：{{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="dodel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页 -->
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2,5,10,20]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹窗 -->
      <el-dialog :visible.sync="showDialog" title="新增员工">
        <emDialog :show-dialog="showDialog" @close="showDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
// import PageTools from '@/components/PageTools'
import EmployeeEnum from '@/constant/employees'
import { getEmployee, delEmployee, addEmployee } from '@/api/employees'
import emDialog from './empDialog.vue'
// 枚举装换 树形
const hireType = EmployeeEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})

console.log('枚举信息', EmployeeEnum.hireType, hireType)
export default {
  components: {
    emDialog
  },
  data() {
    return {
      showDialog: false, // 新增员工的弹窗
      total: 0,
      list: [],
      page: 1,
      size: 2

    }
  },
  created() {
    this.loadgetEmployee()
  },
  methods: {
    dataForm(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1 获取表头
      const one = list[0]
      let header = []
      if (one) {
        header = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      // 2 将每一个对象中的值存储到数组中 将每个数组存储到大数组
      const data = list.map(item => {
        return Object.values(item)
      })
      console.log(header)
      console.log(data)
      return { header, data }
    },
    async handleDownload() {
      // 1 发送请求 拿到数据
      try {
        const res = await getEmployee(this.page, this.size)
        if (res.code !== 10000) return
        console.log(res.data.rows, 'res.data.rows')
        // 2 将获取的数据转换成excel 格式  header data
        const { header, data } = this.dataForm(res.data.rows)
        //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
        import('@/vendor/Export2Excel').then(excel => {
        // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          console.log(excel, 'excel')
          // const tHeader = ['姓名', '年龄']
          // const data = [['曹操', 40], ['刘备', 45]]
          //  excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 新增
    async addEmployee() {
      try {
        const res = await addEmployee(1)
        console.log('addEmployee', res)
        // 保存数据
      } catch (err) {
        console.log('addEmployee', err)
      }
    },
    // 删除
    dodel(id) {
      this.$confirm('你真要删除吗').then(async() => {
        try {
          const res = await delEmployee(id)
          console.log('delEmployee', res)
          // 删除当前页只有最后一条 page需要减一
          if (this.list.length === 1) {
            this.page--
            // 数据只剩一条时 page默认要设置成一 否则程序报错
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadgetEmployee()
        // 保存数据
        } catch (err) {
          console.log('delEmployee', err)
        }
      }).catch(err => err)
    },

    // 分页函数
    // 会自动接收当前点击的页码
    hCurrentChange(val) {
      // alert(curPage)
      // 1. 更新页码
      this.page = val
      // 2. 重发请求
      this.loadgetEmployee()
    },
    // 每页几条
    hSizeChange(val) {
      // alert(size)
      // 1. 更新每页的条数
      this.page = 1
      this.size = val
      // 2. 重发请求
      this.loadgetEmployee()
    },
    formatEmployment(id) {
      // 从hireType中 通过id找到对应的元素的value
      return hireType[id]
      // return  ? '正式' : '非正式'
    },
    // 下拉员工列表
    async loadgetEmployee() {
      try {
        const res = await getEmployee(this.page, this.size)
        console.log('getEmployee', res)
        this.list = res.data.rows
        this.total = res.data.total
      // 保存数据
      } catch (err) {
        console.log('getEmployee', err)
      }
    }
  }
}
</script>
